//
//  WBUserAccount.swift
//  微博
//
//  Created by 康智桐 on 2018/4/21.
//  Copyright © 2018年 Kk. All rights reserved.
//

import UIKit

let accountFile:NSString = "useraccount.json"


//用户账户信息
class WBUserAccount: NSObject {
    //访问令牌
    var access_token: String? //= "2.009cq9xFYTEuSC0a25c7b83d0KDqpd"
    //用户代号
    var uid: String?
    //Token声明周期，单位是秒
    var expires_in:TimeInterval = 0 {
        didSet{
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    //过期日期
    var expiresDate:Date?
    
    //用户昵称
    var screen_name :String?
    //用户头像
    var avatar_large:String?
    
    
    override var description: String{
        return yy_modelDescription()
    }
    
    
    
    override init() {
        
        super.init()
        //从磁盘加载保存的文件
        
        //加载磁盘文件到二进制数据
        guard let path = accountFile.cz_appendDocumentDir(),
                let data = NSData(contentsOfFile: path),
        let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String:Any]

        else {
            return
        }
        
        
        //使用字典设置属性值
        yy_modelSet(with: dict ?? [:])
        
        
        //测试过期日期
        // expiresDate = Date(timeIntervalSinceNow: -3600 * 24)
        
        //判断token是否过期
        if expiresDate?.compare(Date()) != .orderedDescending {
            print("账户过期了")
            
            //清空 token
            access_token = nil
            uid = nil
            
            //删除账户文件
            _ = try? FileManager.default.removeItem(atPath: path)
            
            
            
        }
    }
    
    
    
    
    /*
     保存用户账户信息的方法
     1.偏好设置
     2.沙盒-归档/plist/json
     3.数据库
     4.钥匙串访问
     */
    
    
    
    
    func saveAccount(){
        //模型转字典
        var dict = (self.yy_modelToJSONObject() as? [String:Any]) ?? [:]
        
        
        //删除 expires_in 
        dict.removeValue(forKey: "expires_in")
        
        //字典序列化data
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
            let filePath = accountFile.cz_appendDocumentDir()
            else {
                return
        }
        
        //写入磁盘
        (data as NSData).write(toFile: filePath, atomically: true)
        
        print("用户账户保存成功\(filePath)")
    }
    
    
}
